package com.bailiban.user.service;

import com.bailiban.common.util.IdWorker;
import com.bailiban.user.entity.User;
import com.bailiban.user.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author zhulang
 * @Classname UserService
 * @Description UserService
 */
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private BCryptPasswordEncoder bCrypt;

    public User findById(String id) {
        return userMapper.selectById(id);
    }

    public List<User> findAll() {
        return userMapper.selectList(null);
    }

    /**
     * 发送短信验证码：6位数
     *
     * @param phone
     */
    public void sendSms(String phone) {
        int min = 100000;
        int max = 999999;
        Random random = new Random();
        int code = random.nextInt(max);
        code = code < min ? code + min : code;
        System.out.println(phone + "验证码为：" + code);
//        将验证码存储到redis中，同时设置有效期为5分钟
        redisTemplate.boundValueOps("sms_code_phone" + phone)
                .set("sms_code" + code, 5, TimeUnit.MINUTES);
        HashMap<String, String> map = new HashMap<>();
        map.put("code", code + "");
        map.put("phone", phone);
        rabbitTemplate.convertAndSend("sms", map);
    }

    public void regist(User user, String code) {
        //从redis服务器中取验证码
        String codeStr = (String) redisTemplate.boundValueOps("sms_code_phone" + user.getMobile()).get();
        if (StringUtils.isEmpty(codeStr)) {
            //验证码为空
            throw new RuntimeException("验证码已过期，请重新获取");
        } else if (!codeStr.equals("sms_code" + code)) {
            throw new RuntimeException("验证码输入有误，请重新获取");
        } else {
//            验证码是对的，进行注册
            user.setId(idWorker.nextId() + "");
            user.setLastdate(new Date());
            user.setOnline(0L);
            user.setRegdate(new Date());
            user.setUpdatedate(new Date());
            user.setFanscount(0);
            user.setFollowcount(0);
//            对用户注册密码进行加密
            user.setPassword(bCrypt.encode(user.getPassword()));
            userMapper.insert(user);
        }
    }

    public User login(String mobile, String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", mobile);
        User user = userMapper.selectOne(queryWrapper);
        if (user != null && bCrypt.matches(password, user.getPassword())) {
            //用户登录成功
            return user;
        }
        return null;

    }

    public void delete(String id) {
        userMapper.deleteById(id);
    }

    public void update(User user) {
        userMapper.updateById(user);
    }
}
